package cn.wqb.bpp.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/**
 * 依赖
 * <dependency>
 * <groupId>com.google.zxing</groupId>
 * <artifactId>javase</artifactId>
 * <version>3.3.0</version>
 * </dependency>
 */

public class QRCodeGenerator {

    /**
     * 将内容转换成二维码图片并保存到指定路径
     *
     * @param content
     * @param size
     * @param saveFullPath
     */
    public static void generateQRCodeImage(String content, int size, String saveFullPath) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, size, size);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        Path path = FileSystems.getDefault().getPath(saveFullPath);
        try {
            MatrixToImageWriter.writeToPath(deleteBorder(bitMatrix), "PNG", path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将内容转换成二维码字节数组以便传给Web页面显示（可以通过Thymeleaf显示）
     * Web页面中直接将base64的字符串赋值到<img>的src属性里即可
     *
     * @param content
     * @param size
     */
    public static String generateQRCodeBase64(String content, int size) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, size, size);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        try {
            MatrixToImageWriter.writeToStream(deleteBorder(bitMatrix), "PNG", pngOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] pngData = pngOutputStream.toByteArray();
        return "data:img/png;base64," + Base64.encodeBase64String(pngData);
    }

    /**
     * 去白边
     */
    private static BitMatrix deleteBorder(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }
        return resMatrix;
    }

}
